Skip to main content

Button Components

Button

  • Button은 React Native에서 기본 제공하는 클릭 가능한 버튼 컴포넌트
  • 터치 이벤트를 감지하고 사용자 입력을 처리할 수 있음
App.tsx
import { useState } from "react";
import { Button, SafeAreaView, Text } from "react-native";

export default function App() {
const [state, setState] = useState<boolean>(false);

return (
<SafeAreaView
style={{ flex: 1, justifyContent: "center", alignItems: "center" }}
>
<Button
title={state ? "누르세요!" : "눌렀음!"}
onPress={() => setState(!state)}
/>
<Text>{state ? "Hello World!" : ""}</Text>
</SafeAreaView>
);
}

Image

note

Button은 onPress속성을 통해 눌렀을 때, 어떤 이벤트를 처리할 지 함수를 작성하면 된다.

TouchableOpacity

  • TouchableOpacity는 React Native에서 터치 이벤트를 감지할 수 있는 컴포넌트
  • 버튼을 클릭할 때 투명도가 변경되어 사용자가 터치했음을 시각적으로 제공
  • Button 컴포넌트보다 스타일링이 자유롭고, 다양한 UI 요소를 감쌀 수 있음
App.tsx
import { useState } from "react";
import { Text, TouchableOpacity, SafeAreaView } from "react-native";

export default function App() {
const [count, setCount] = useState<number>(0);

return (
<SafeAreaView
style={{ flex: 1, justifyContent: "center", alignItems: "center" }}
>
<TouchableOpacity
style={{ backgroundColor: "#3498db", padding: 15, borderRadius: 10 }}
onPress={() => setCount(count + 1)}
delayPressOut={3000}
>
<Text style={{ color: "white", fontSize: 18 }}>누르세요!</Text>
</TouchableOpacity>
<Text>누른 횟수 : {count}</Text>
</SafeAreaView>
);
}

Image

note

TouchableOpacity는 Button과 달리 TouchableOpacity 버튼안 직접 child 컴포넌트를 작성할 수 있다.
즉, Button보다 스타일링 및 기능이 확장된 컴포넌트이다.

delayPressOut을 이용하여 터치가 끝난 후, 3000ms(3초) 후에 다시 버튼이 활성화 된 것을 볼 수 있다.

TouchableOpacity 속성 정리

속성명타입기본값설명
onPress() => void터치 시 실행할 함수
activeOpacitynumber0.2터치 시 투명도 (0~1 사이의 값)
disabledbooleanfalse버튼 비활성화 여부
onLongPress() => void길게 눌렀을 때 실행할 함수
delayPressInnumber터치 시작 후 onPress 이벤트까지의 지연 시간 (ms)
delayPressOutnumber터치 해제 후 애니메이션 지속 시간 (ms)
styleobject스타일 적용

TouchableHighlight

  • TouchableHighlight는 React Native에서 터치 이벤트를 감지하는 컴포넌트
  • TouchableOpacity와 유사하지만, 버튼을 누를 때 배경색이 변경되는 효과가 추가됨
  • TouchableOpacity보다 터치 했을 때, 시각적으로 명확하게 표현
App.tsx
import { useState } from "react";
import { Text, SafeAreaView, TouchableHighlight } from "react-native";

export default function App() {
const [count, setCount] = useState<number>(0);

return (
<SafeAreaView
style={{ flex: 1, justifyContent: "center", alignItems: "center" }}
>
<TouchableHighlight
style={{ backgroundColor: "#3498db", padding: 15, borderRadius: 10 }}
onPress={() => setCount(count + 1)}
underlayColor={"#1f618d"}
delayPressOut={3000}
>
<Text style={{ color: "white", fontSize: 18 }}>누르세요!</Text>
</TouchableHighlight>
<Text>누른 횟수 : {count}</Text>
</SafeAreaView>
);
}

Image

note

TouchableHighlight는 TouchableOpacity와 사용법은 같다.
차이점은 TouchableHighlight은 underlayColor로 버튼을 누른 후, 색상을 별도로 지정할 수 있다.

Pressable

  • React Native에서 보다 세밀한 터치 이벤트를 제어할 수 있는 컴포넌트
  • TouchableOpacity, TouchableHighlight보다 더 다양한 상태(pressed, hovered 등)를 감지 가능
  • 버튼뿐만 아니라 모든 UI 요소에 적용 가능
App.tsx
import { Text, SafeAreaView, Pressable, View } from "react-native";

export default function App() {
return (
<SafeAreaView
style={{ flex: 1, justifyContent: "center", alignItems: "center" }}
>
<Pressable
style={({ pressed }) => ({
backgroundColor: pressed ? "#2980b9" : "#3498db",
padding: 15,
borderRadius: 10,
})}
onPress={() => console.log("onPress 실행")}
onLongPress={() => console.log("onLongPress 실행")}
onPressIn={() => console.log("onPressIn 실행")}
onPressOut={() => console.log("onPressOut 실행")}
>
<Text style={{ color: "white", fontSize: 18 }}>누르세요!</Text>
</Pressable>
</SafeAreaView>
);
}
note
  • 버튼을 짧게 눌렀을 경우

Image

  • 버튼을 길게 눌렀을 경우

Image

Pressable 속성 정리

속성명타입기본값설명
onPress() => void버튼을 짧게 눌렀을 때 호출
onLongPress() => void버튼을 길게 눌렀을 때 호출
onPressIn() => void터치가 시작될 때 호출
onPressOut() => void터치가 끝날 때 호출
style(state) => objectpressed 상태를 활용해 동적 스타일 적용
disabledbooleanfalse버튼 비활성화 여부
info

언제 어떤 버튼을 써야 할까?

버튼 종류추천 상황주요 특징
Button기본 버튼이 필요할 때스타일 커스터마이징 제한적
TouchableOpacity일반적인 터치 효과가 필요할 때터치 시 투명도 변경
TouchableHighlight터치 시 배경색 변경이 필요할 때underlayColor색상 변경 가능
Pressable세밀한 터치 이벤트가 필요할 때onPressIn, onPressOut세밀한 이벤트 처리 가능

Switch

  • (On/Off)를 전환할 수 있는 토글 버튼
App.tsx
import { useState } from "react";
import { Switch, Text, SafeAreaView } from "react-native";

export default function App() {
const [isEnabled, setIsEnabled] = useState<boolean>(false);

return (
<SafeAreaView
style={{
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: isEnabled ? "black" : "white",
marginTop: 30,
}}
>
<Text style={{ color: isEnabled ? "white" : "black" }}>
스위치 상태: {isEnabled ? "ON" : "OFF"}
</Text>
<Switch
value={isEnabled}
onValueChange={() => setIsEnabled(!isEnabled)}
trackColor={{ false: "#767577", true: "#81b0ff" }}
thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
/>
</SafeAreaView>
);
}

Image

note

Switch의 value속성에 현재 상태를 포함한 boolean값을 전달 한다.
onValueChange를 통해 토글 버튼을 눌렀을 때, 값을 어떻게 변화시킬지에 대한 함수를 넣는다.
trackColortruefalse일 경우 토글아이콘의 배경에 대한 색상을 정의한다.
thumbColor에는 토글의 버튼에 대한 색상을 정의한다.

Switch 속성 정리

속성명타입기본값설명
valuebooleanfalse현재 Switch의 상태
onValueChange(value: boolean) => void상태 변경 시 호출되는 함수
disabledbooleanfalsetrue로 설정하면 비활성화
trackColor{ false: string, true: string }{}스위치 배경 색상 설정
thumbColorstring""버튼(동그란 부분) 색상 설정
ios_backgroundColorstring""iOS에서 비활성화된 배경 색상 설정

Slider

  • 사용자가 드래그하여 값을 조정할 수 있는 입력 컨트롤
  • 음량 조절, 밝기 조절 등 연속적인 값 조절이 필요한 경우에 사용
// slider 설치
npm install @react-native-community/slider
App.tsx
import Slider from "@react-native-community/slider";
import React, { useState } from "react";
import { Text, SafeAreaView } from "react-native";

export default function App() {
const [sliderValue, setSliderValue] = useState(50);

return (
<SafeAreaView
style={{
flex: 1,
justifyContent: "center",
alignItems: "center",
marginTop: 50,
}}
>
<Text style={{ fontSize: 30 }}>슬라이더 값: {sliderValue}</Text>
<Slider
style={{ width: 200, height: 50 }}
minimumValue={0}
maximumValue={100}
step={5}
value={sliderValue}
onValueChange={(e) => setSliderValue(e)}
minimumTrackTintColor="blue"
maximumTrackTintColor="gray"
thumbTintColor="skyblue"
/>
</SafeAreaView>
);
}

Image

Slider 속성 정리

속성명타입기본값설명
valuenumber현재 Slider 값
onValueChange(value: number) => void값이 변경될 때 호출되는 함수
minimumValuenumber0최소 값
maximumValuenumber1최대 값
stepnumber값이 증가하는 단위 (예: 1이면 1씩 증가)
minimumTrackTintColorstringblue진행된 부분 색상
maximumTrackTintColorstringgray진행되지 않은 부분 색상
thumbTintColorstringwhite슬라이더 핸들 색상
disabledbooleanfalsetrue로 설정하면 슬라이더 비활성화